package site.lanmushan.framework.authorization.service;

import com.alibaba.fastjson.JSONObject;
import com.nimbusds.jose.JOSEException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import site.lanmushan.framework.authorization.constant.TokenConstants;
import site.lanmushan.framework.authorization.domain.TokenBo;
import site.lanmushan.framework.authorization.util.JwtUtil;

import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.util.Map;

/**
 * @author Administrator
 */
@Slf4j
@Service
public class JwtTokenService extends AbstractTokenService {
    @Override
    public TokenBo encryptionToken(JSONObject obj, String secretKey, Integer expires) {
        Map<String, Object> json = new JSONObject();
        json.put(TokenConstants.DATA_KEY, obj);
        Long expiresTime = System.currentTimeMillis() + expires * 1000;
        json.put(TokenConstants.EXPIRE_TIME_KEY, expiresTime);
        try {
            TokenBo tokenBo = new TokenBo();
            tokenBo.setToken(JwtUtil.createTokenHS512(json, secretKey));
            tokenBo.setExpireTime(expiresTime);
            tokenBo.setExpires(expires);
            return tokenBo;
        } catch (JOSEException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    public <T> T decryptToken(String token, String secretKey, Class<T> t) {
        try {
            Map<String, Object> result = JwtUtil.parseToken512(token, secretKey);
            if (result == null) {
                return null;
            }
            Long expiresTime = (Long) result.get(TokenConstants.EXPIRE_TIME_KEY);
            if (expiresTime == -1 || expiresTime > System.currentTimeMillis()) {
                net.minidev.json.JSONObject jsonObject = (net.minidev.json.JSONObject) result.get(TokenConstants.DATA_KEY);
                return JSONObject.parseObject(jsonObject.toJSONString(), t);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (JOSEException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public <T> T decryptTokenException(String token, String secretKey, Class<T> t) {
        return null;
    }


}
